﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Text.RegularExpressions;
using System.Web;
using OptimizerPrime.BaseClasses;
using OptimizerPrime.Configs;
using Utilities.Events.EventArgs;
using Utilities.Web.ExtensionMethods;
#endregion

namespace OptimizerPrime.HttpModules.Compression
{
    /// <summary>
    /// HTTP Module that deals with compression
    /// </summary>
    public class Compression : BaseModule
    {
        #region Private Consts
        private const string GZIP = "gzip";
        private const string DEFLATE = "deflate";
        #endregion

        #region Variables
        protected override string SettingsName { get { return "CompressionModule"; } }
        #endregion

        #region Public Functions

        /// <summary>
        /// Disposes of the object
        /// </summary>
        public override void Dispose()
        {
        }

        /// <summary>
        /// Initializes the object
        /// </summary>
        /// <param name="context">The current HttpApplication</param>
        public override void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
            context.Error += new EventHandler(context_Error);
        }

        #endregion

        #region Events

        /// <summary>
        /// Removes compression in the case of an error
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_Error(object sender, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)sender;
            Application.Response.Filter = null;
        }

        /// <summary>
        /// Adds the compression in there at this step
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            if (((CompressionConfig)Settings).Compress)
            {
                if (!OnStart(new OnStartEventArgs()))
                    return;
                HttpApplication Application = (HttpApplication)sender;
                HttpRequest Request = Application.Request;
                string CurrentPath = Request.Path.ToLowerInvariant();
                foreach (string Page in ((CompressionConfig)Settings).IgnorePages)
                {
                    Regex TempRegex = new Regex(Page, RegexOptions.IgnoreCase);
                    if (TempRegex.IsMatch(CurrentPath))
                        return;
                }
                if ((Application.Context.CurrentHandler is System.Web.UI.Page
                    && Application.Request["HTTP_X_MICROSOFTAJAX"] == null
                    && Application.Request.Params["_TSM_CombinedScripts_"] == null)
                    || Application.Context.CurrentHandler is System.Web.Mvc.MvcHandler)
                {
                    if (Application.Context.IsEncodingAccepted(DEFLATE))
                    {
                        Application.Response.Filter = new UglyStream(Application.Response.Filter, DEFLATE);
                        Application.Context.SetEncoding(DEFLATE);
                    }
                    else if (Application.Context.IsEncodingAccepted(GZIP))
                    {
                        Application.Response.Filter = new UglyStream(Application.Response.Filter, GZIP);
                        Application.Context.SetEncoding(GZIP);
                    }
                }
                OnEnd(new OnEndEventArgs());
            }
        }

        #endregion
    }
}